package com.jimmy.proxy.cglibproxy;

import com.jimmy.proxy.jdkproxy.UserService;
import com.jimmy.proxy.jdkproxy.UserServiceImpl;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @version 1.0
 * @ ClassName UserCglibProxy
 * <p> TODO
 * @ author JIMMY
 * @ Date 2020/11/3 0003 下午 7:22
 */
public class UserCglibProxy implements MethodInterceptor {
    private UserService userService;
    public UserService createProxy(UserService userService){
        this.userService = userService;
        //创建一个Enhancer对象
        Enhancer enhancer = new Enhancer();
        //设置Enhancer对象的父类
        enhancer.setSuperclass(userService.getClass());
        //设置代理对象回调方法
        enhancer.setCallback(this);
        //获取代理对象
        return (UserService) enhancer.create();
    }

    //method是新的方法，字节码是全新的
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        if (method.getName().equals("save")){
            System.out.println("before");
        }
        Object invoke = method.invoke(userService, null);
        if (method.getName().equals("save")){
            System.out.println("after");
        }
        return invoke;
    }
    public static void main(String[] args) {
        UserService userService = new UserServiceImpl();
        UserService user = new UserCglibProxy().createProxy(userService);
        user.save();
    }
}
